package windows;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ContainerAdapter;
import java.awt.event.ContainerEvent;
import java.io.File;
import java.util.HashMap;
import java.util.Locale;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JProgressBar;
import javax.swing.JTabbedPane;
import javax.swing.UIManager;
import chrriis.dj.nativeswing.swtimpl.NativeInterface;
import langBundle.MsgControl;
import sqlServer.AppConnection;
import windowUnits.ButtonTabComponent;
import windowUnits.HistoryToolBar;
import windowUnits.ProgressBarThread;
import xml.XmlWebSet;
import xml.xmlSettings;

import com.swtdesigner.SwingResourceManager;
import javax.swing.ImageIcon;
import javax.swing.border.LineBorder;

public class MainAppW {

	private JFrame frame;
	private xmlSettings initXml = new xmlSettings();
	private static MsgControl msgBundle;
	private final JMenuBar menuBar = new JMenuBar();
	private final JMenu mainSetMenu = new JMenu();
	private final JMenuItem mainControlMenuItem = new JMenuItem();
	private final JMenuItem configMenuItem = new JMenuItem();
	private final JMenuItem mediaManagerMenuItem = new JMenuItem();
	private final JMenuItem userManagerMenuItem = new JMenuItem();
	private final JMenuItem connectMenuItem = new JMenuItem();
	private final JMenu menu = new JMenu();
	private final JMenuItem webContentMenuItem = new JMenuItem();
	private final JTabbedPane tabbedPane = new JTabbedPane();
	private final JPanel statusBarPanel = new JPanel();
	private final HistoryToolBar historyToolBar = new HistoryToolBar();
	private final JMenuItem newItemMenuItem = new JMenuItem();
	private final JMenu installMenu = new JMenu("Create Web");
	private final JMenuItem installWeb = new JMenuItem("Install Web Page");
	private final JMenuItem copyWeb = new JMenuItem("Copy Web Page");
	private final JMenuItem moveWeb = new JMenuItem("Move Web Page");
	private final String userName = System.getProperty("user.name");
	public static final String WINLANG = System.getProperty("user.language");
	private XmlWebSet xmSet;
	private final JMenu webPagesMenu = new JMenu();

	private final JLabel jContentManagmentLabel = new JLabel();
	/**
	 * Launch the application
	 * @param args 
	 */
	public static void main(String args[]) {
		try {
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch (Throwable e) {
			JOptionPane.showMessageDialog(new JFrame(),e.getMessage());
		}
		try {
			NativeInterface.open();
			MainAppW window = new MainAppW();
			window.frame.setVisible(true);
			System.out.println("Window's Username: "+window.userName);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the application
	 */
	public MainAppW() {
		
		int resp = 0;
		String pass = null;
		final JPasswordField pwd = new JPasswordField();
		File isSetXmlFile = new File("settings/"+userName+"_WebSetup.xml");
		while(true){
		if(!isSetXmlFile.exists()){
			try {
				initXml.setLanguage(WINLANG);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				JOptionPane.showConfirmDialog(null, e1.getMessage(), "Problem with setup file", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
				
			}
			while(true){
				pwd.setText("");
				final JPasswordField pwd2 = new JPasswordField();
				Object[] message = { userName+" please create password for future login \n\n Password", pwd,"Password test: \n", pwd2 };
				JOptionPane jop = new JOptionPane(message,
		        JOptionPane.QUESTION_MESSAGE,
		        JOptionPane.OK_CANCEL_OPTION);
		      JDialog dialog = jop.createDialog(null,"Enter password");
		      dialog.addComponentListener(new ComponentAdapter(){
		        public void componentShown(ComponentEvent e){
		        	pwd.requestFocusInWindow();
		        }
		      });
		      dialog.setVisible(true);
		      resp = (Integer)jop.getValue();
		      dialog.dispose();
				pass = new String(pwd.getPassword());
				String pass2 = new String(pwd2.getPassword());
				if(resp == JOptionPane.CANCEL_OPTION)
					System.exit(0);
				if(!pass.equals(pass2)){
					JOptionPane.showConfirmDialog(null, "Wrong tested password", "Wrong Test Password", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
				}else{
					break;
				}
			}
		}else{
			
			Object[] message = { userName+" please login \n", pwd };
		      JOptionPane jop = new JOptionPane(message,
		        JOptionPane.QUESTION_MESSAGE,
		        JOptionPane.OK_CANCEL_OPTION);
		      JDialog dialog = jop.createDialog(null,"Enter password");
		      dialog.addComponentListener(new ComponentAdapter(){
		        public void componentShown(ComponentEvent e){
		        	pwd.requestFocusInWindow();
		        }
		      });
		      dialog.setVisible(true);
		      resp = (Integer)jop.getValue();
		      dialog.dispose();
		      if(resp == JOptionPane.OK_OPTION){
		    	  pass = String.valueOf(pwd.getPassword());
		      }
			
			
			//pass = new String(pwd.getPassword());
		}
		
		if(resp == JOptionPane.OK_OPTION) {
		   
		   
		   try {
			xmSet = new XmlWebSet(userName,pass);
			System.out.println("Window's Username: "+XmlWebSet.getMdPsw(pass));
			break;
		   } catch (Exception e) {
				// TODO Auto-generated catch block
				JOptionPane.showConfirmDialog(null, "Wrong password try again", "Wrong Password", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
				e.printStackTrace();
				pwd.setText("");
				//System.exit(0);
			}
		   
		}else{
			System.exit(0);	
			break;
		}
		}
		
		jbInit();
	}

	/**
	 * Initialize the contents of the frame
	 */
	public static MsgControl getMsgBundle(){
		return msgBundle;
	}
	
	private void jbInit() {
				
		msgBundle = new MsgControl(initXml.getLanguage());
		
		frame = new JFrame();
		frame.setIconImage(SwingResourceManager.getImage(MainAppW.class, "/icons/mainIcon.png"));
		frame.setTitle("Universal J Content Manager");
		frame.setBounds(100, 100, 961, 805);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		frame.setJMenuBar(menuBar);
		
		menuBar.add(mainSetMenu);
		mainSetMenu.addActionListener(new MainSetMenuActionListener());
		mainSetMenu.setIcon(SwingResourceManager.getIcon(MainAppW.class, "/icons/mainIcon.png"));
		mainSetMenu.setText("Main Menu");
		msgBundle.setMsgByName(mainSetMenu,"mainContentMenu");
		
		mainSetMenu.add(mainControlMenuItem);
		mainControlMenuItem.setIcon(SwingResourceManager.getIcon(MainAppW.class, "/icons/options.png"));
		mainControlMenuItem.setText("Main Control");
		msgBundle.setMsgByName(mainControlMenuItem,"newItemMenuItem");
		installMenu.setIcon(new ImageIcon(MainAppW.class.getResource("/icons/blog.png")));
		
		mainSetMenu.add(installMenu);
		msgBundle.setMsgByName(installMenu,"installMenu");
		installWeb.addActionListener(new InstallWebItemActionListener());
		installWeb.setIcon(SwingResourceManager.getIcon(MainAppW.class, "/icons/base_r.png"));
		
		installMenu.add(installWeb);
		msgBundle.setMsgByName(installWeb,"installWeb");
		
		installMenu.add(copyWeb);
		msgBundle.setMsgByName(copyWeb,"copyWeb");
		
		installMenu.add(moveWeb);
		msgBundle.setMsgByName(moveWeb,"moveWeb");

		mainSetMenu.addSeparator();
		
		mainSetMenu.add(configMenuItem);
		configMenuItem.setIcon(SwingResourceManager.getIcon(MainAppW.class, "/icons/spanner_48.png"));
		configMenuItem.setText("Configuration");
		msgBundle.setMsgByName(configMenuItem,"newItemMenuItem_1");
		
		mainSetMenu.add(mediaManagerMenuItem);
		mediaManagerMenuItem.setIcon(SwingResourceManager.getIcon(MainAppW.class, "/icons/folder_48.png"));
		mediaManagerMenuItem.setText("Media Manager");
		msgBundle.setMsgByName(mediaManagerMenuItem,"newItemMenuItem_2");
		
		mainSetMenu.add(userManagerMenuItem);
		userManagerMenuItem.setIcon(SwingResourceManager.getIcon(MainAppW.class, "/icons/group.png"));
		userManagerMenuItem.setText("User Manager");
		msgBundle.setMsgByName(userManagerMenuItem,"newItemMenuItem_4");	
		
		mainSetMenu.add(webContentMenuItem);
		webContentMenuItem.addActionListener(new WebContentMenuItemActionListener());
		webContentMenuItem.setIcon(SwingResourceManager.getIcon(MainAppW.class, "/icons/star.png"));
		webContentMenuItem.setText("Web Content");
		msgBundle.setMsgByName(webContentMenuItem,"webContentMenuItem");

		mainSetMenu.addSeparator();
		
		mainSetMenu.add(connectMenuItem);
		connectMenuItem.addActionListener(new ConnectMenuItemActionListener());
		connectMenuItem.setIcon(SwingResourceManager.getIcon(MainAppW.class, "/icons/base_x.png"));
		connectMenuItem.setText("Connect");
		msgBundle.setMsgByName(connectMenuItem,"newItemMenuItem_3");
		
		menuBar.add(webPagesMenu);
		webPagesMenu.setIcon(SwingResourceManager.getIcon(MainAppW.class, "/icons/webPages.png"));
		webPagesMenu.setText("Web Pages");
		msgBundle.setMsgByName(webPagesMenu,"webPagesMenu");
		
		setWebPagesMenu();
		
		menuBar.add(menu);
		menu.setIcon(SwingResourceManager.getIcon(MainAppW.class, "/icons/stopplay.png"));
		menu.setText("Show");
		msgBundle.setMsgByName(menu,"menu");
		
		menu.add(newItemMenuItem);
		newItemMenuItem.addActionListener(new NewItemMenuItemActionListener());
		newItemMenuItem.setIcon(SwingResourceManager.getIcon(MainAppW.class, "/icons/folder_48.png"));
		newItemMenuItem.setText("Changes queue");
		msgBundle.setMsgByName(newItemMenuItem,"newItemMenuItem");
		
		frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
		tabbedPane.addContainerListener(new TabbedPaneContainerListener());
		tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
		
		frame.getContentPane().add(statusBarPanel, BorderLayout.SOUTH);
		statusBarPanel.setLayout(new BorderLayout());
		jContentManagmentLabel.setPreferredSize(new Dimension(50,20));
		statusBarPanel.add(jContentManagmentLabel, BorderLayout.WEST);
		jContentManagmentLabel.setText(" J CMS");
		
		historyToolBar.setBorder(new LineBorder(Color.GRAY, 1, true));
		historyToolBar.setMargin(new Insets(0, 4, 0, 4));
		frame.getContentPane().add(historyToolBar, BorderLayout.EAST);
		historyToolBar.setupToolBar();
		msgBundle.setMsgByName(historyToolBar,"historyToolBar");
		
		System.currentTimeMillis();
		//final FlowLayout flowLayout = new FlowLayout();
		//System.currentTimeMillis();
		
		
	}
	
	public void setWebPagesMenu(){
		webPagesMenu.removeAll();
		//Insert Web pages into menu
		HashMap <Integer,String> installedWebs  = new HashMap<Integer,String>();
		installedWebs = xmSet.getInstalledWebs();
		for(int i=0;i<installedWebs.size();i++){
			JMenu webPageToMenu = new JMenu(installedWebs.get(i));
			JMenuItem pageSetup = new JMenuItem("Web Configuration");
			msgBundle.setMsgByName(pageSetup,"pageSetup");
			pageSetup.setActionCommand(installedWebs.get(i));
			pageSetup.addActionListener(new WebPagesConfigActionListener());
			pageSetup.setIcon(SwingResourceManager.getIcon(MainAppW.class, "/icons/foward.png"));
			JMenuItem webContentMenu = new JMenuItem("Web Configuration");
			webContentMenu.setActionCommand(installedWebs.get(i));
			webContentMenu.addActionListener(new WebContentMenuItemActionListener());
			webContentMenu.setIcon(SwingResourceManager.getIcon(MainAppW.class, "/icons/star.png"));
			webContentMenu.setText("Web Content");
			msgBundle.setMsgByName(webContentMenu,"webContentMenuItem");	
			webPageToMenu.add(pageSetup);
			webPageToMenu.add(webContentMenu);
			webPagesMenu.add(webPageToMenu);
		}
	}
	
	private class WebPagesConfigActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			webPagesConfig_actionPerformed(e);
		}
	}
	private class MainSetMenuActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			mainSetMenu_actionPerformed(e);
		}
	}
	private class ConnectMenuItemActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			connectMenuItem_actionPerformed(e);
		}
	}
	private class WebContentMenuItemActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			webContentMenuItem_actionPerformed(e);
		}
	}
	private class NewItemMenuItemActionListener implements ActionListener {
		public void actionPerformed(ActionEvent arg0) {
			newItemMenuItem_actionPerformed(arg0);
		}
	}
	private class InstallWebItemActionListener implements ActionListener {
		public void actionPerformed(ActionEvent arg0) {
			installWeb_actionPerformed(arg0);
		}
	}
	private class TabbedPaneContainerListener extends ContainerAdapter {
		public void componentRemoved(ContainerEvent arg0) {
			tabbedPane_componentRemoved(arg0);
		}
	}
	
	protected void webPagesConfig_actionPerformed(ActionEvent e) {
		System.out.println(e.getActionCommand());
		SetupPanel sp = new SetupPanel(xmSet,msgBundle,e.getActionCommand());
		JMenuItem itm = (JMenuItem)e.getSource();
		tabbedPane.addTab(itm.getText()+" - "+e.getActionCommand(), SwingResourceManager.getIcon(MainAppW.class, "/icons/foward.png"), sp, null);
		tabbedPane.setSelectedComponent(sp);
		tabbedPane.setTabComponentAt(tabbedPane.getSelectedIndex(), new ButtonTabComponent(tabbedPane));
	}
	// Install Web content to server action
	protected void installWeb_actionPerformed(ActionEvent e) {
		SetupPanel sp = new SetupPanel(xmSet,msgBundle);
		JMenuItem itm = (JMenuItem)e.getSource();
		tabbedPane.addTab(itm.getText(), SwingResourceManager.getIcon(MainAppW.class, "/icons/foward.png"), sp, null);
		tabbedPane.setSelectedComponent(sp);
		tabbedPane.setTabComponentAt(tabbedPane.getSelectedIndex(), new ButtonTabComponent(tabbedPane));
	}
	
	protected void mainSetMenu_actionPerformed(ActionEvent e) {
	}
	protected void connectMenuItem_actionPerformed(ActionEvent e) {
		JOptionPane.showMessageDialog(frame,initXml.getLanguage());
		/*
		if(applicationConnect.isConnected()){
			applicationConnect.closeConnection();
		}else{
			applicationConnect.createConnection();
		}
		if(applicationConnect.isConnected()){
			connectMenuItem.setIcon(SwingResourceManager.getIcon(MainAppW.class, "/icons/base_r.png"));
		}else{
			connectMenuItem.setIcon(SwingResourceManager.getIcon(MainAppW.class, "/icons/base_x.png"));
		}
		*/
	}
	protected void webContentMenuItem_actionPerformed(ActionEvent e) {
		ProgressBarThread pg = new ProgressBarThread(statusBarPanel,"Connecting: ");
		pg.start();
		PageContent pc = new PageContent(msgBundle,xmSet,e.getActionCommand(),pg,historyToolBar,statusBarPanel); 
		tabbedPane.addTab(e.getActionCommand(), SwingResourceManager.getIcon(MainAppW.class, "/icons/star.png"), pc, null);
		tabbedPane.setSelectedComponent(pc);
		tabbedPane.setTabComponentAt(tabbedPane.getSelectedIndex(), new ButtonTabComponent(tabbedPane));
		//tabbedPane.setTabComponentAt(1,new ButtonTabComponent(tabbedPane));
	}
	protected void newItemMenuItem_actionPerformed(ActionEvent arg0) {
		if(historyToolBar.isVisible()){
			historyToolBar.setVisible(false);
		}else{
			historyToolBar.setVisible(true);
		}
	}
	protected void tabbedPane_componentRemoved(ContainerEvent arg0) {
		if(arg0.getChild().getClass().getName().equals("winodws.SetupPanel")){
			setWebPagesMenu();
		}else if(arg0.getChild().getClass().getName().equals("winodws.PageContent")){
			((PageContent)arg0.getChild()).closeConnection();
		}
	}
}
